<?php

if (!function_exists('isMobile')) {
    function isMobile()
    {
        $useragent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
        $useragent_commentsblock = preg_match('/.∗?/', $useragent, $matches) > 0 ? $matches[0] : '';


        $mobile_os_list = array('Google Wireless Transcoder', 'Windows CE', 'WindowsCE', 'Symbian', 'Android', 'armv6l', 'armv5', 'Mobile', 'CentOS', 'mowser', 'AvantGo', 'Opera Mobi', 'J2ME/MIDP', 'Smartphone', 'Go.Web', 'Palm', 'iPAQ');
        $mobile_token_list = array('Profile/MIDP', 'Configuration/CLDC-', '160×160', '176×220', '240×240', '240×320', '320×240', 'UP.Browser', 'UP.Link', 'SymbianOS', 'PalmOS', 'PocketPC', 'SonyEricsson', 'Nokia', 'BlackBerry', 'Vodafone', 'BenQ', 'Novarra-Vision', 'Iris', 'NetFront', 'HTC_', 'Xda_', 'SAMSUNG-SGH', 'Wapaka', 'DoCoMo', 'iPhone', 'iPod', 'iPad');

        $found_mobile = checkSubstrs($mobile_os_list, $useragent) || checkSubstrs($mobile_token_list, $useragent_commentsblock);

        if ($found_mobile) {
            return true;
        } else {
            return false;
        }
    }
}

//将以分为单位的price格式改成以元为单位的格式
if (!function_exists('priceIntToFloat')) {
    function priceIntToFloat($price)
    {
        return sprintf("%.2f", ($price / 100));
    }
}

if (!function_exists('checkSubstrs')) {
    function checkSubstrs($substrs, $text)
    {

        foreach ($substrs as $substr) {
            if (false !== strpos($text, $substr)) {
                return true;
            }
        }
        return false;
    }
}

/**
 * 获取随机值
 * @param int $len
 * @return string
 */
if (!function_exists('getSalt')) {
    function getSalt($len = 8, $num = 0)
    {
        $salt = '';
        if ($num == 0) {
            $str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
        } else {
            $str = "0123456789";
        }
        $max = strlen($str) - 1;

        for ($i = 0; $i < $len; $i++) {
            $salt .= $str[rand(0, $max)];
        }

        return $salt;
    }
}

/**
 * 获取加密串
 * @param $str
 * @param $salt
 * @return string
 */
if (!function_exists('encrypt_sha_md5')) {
    function encrypt_sha_md5($str, $salt)
    {
        return sha1(md5($str . $salt));
    }
}

/**
 * @param $url
 * @return mixed
 * curl get
 */
if (!function_exists('curlGet')) {
    function curlGet($url, $cookie = '')
    {
        \Log::debug($url);
        $ch = curl_init();
        $user_agent = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36';
        curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
        // 2. 设置选项，包括URL
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-FORWARDED-FOR:192.168.2.11', 'CLIENT-IP:192.168.2.11'));  //构造IP
        curl_setopt($ch, CURLOPT_REFERER, "http://www.baidu.com/");   //构造来路
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);

        if(!empty($cookie)){
            curl_setopt($ch, CURLOPT_COOKIE, $cookie);
        }

        // 3. 执行并获取HTML文档内容
        $output = curl_exec($ch);
        curl_close($ch);

        return $output;
    }
}

/**
 * @param $url
 * @return mixed
 * curl post
 */
if (!function_exists('curlPost')) {
    function curlPost($url, $data)
    {
        \Log::debug($url);
        $ch = curl_init();
        $user_agent = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36';
        curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
        // 2. 设置选项，包括URL
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);

        // 3. 执行并获取HTML文档内容
        $output = curl_exec($ch);
        curl_close($ch);

        return $output;
    }
}

//获取顶级域名
if (!function_exists('getdomain')) {
    function getdomain($url)
    {
        $host = strtolower($url);
        if (strpos($host, '/') !== false) {
            $parse = @parse_url($host);
            $host = $parse ['host'];
        }
        $topleveldomaindb = array('com', 'edu', 'gov', 'int', 'mil', 'net', 'org', 'biz', 'info', 'pro', 'name', 'museum', 'coop', 'aero', 'xxx', 'idv', 'mobi', 'cc', 'me');
        $str = '';
        foreach ($topleveldomaindb as $v) {
            $str .= ($str ? '|' : '') . $v;
        }

        $matchstr = "[^\.]+\.(?:(" . $str . ")|\w{2}|((" . $str . ")\.\w{2}))$";
        if (preg_match("/" . $matchstr . "/ies", $host, $matchs)) {
            $domain = $matchs ['0'];
        } else {
            $domain = $host;
        }
        return $domain;
    }
}
//将 xml数据转换为数组格式。
if (!function_exists('xml_to_array')) {
    function xml_to_array($xml)
    {
        $reg = "/<(\w+)[^>]*>([\\x00-\\xFF]*)<\\/\\1>/";
        if (preg_match_all($reg, $xml, $matches)) {
            $count = count($matches[0]);
            for ($i = 0; $i < $count; $i++) {
                $subxml = $matches[2][$i];
                $key = $matches[1][$i];
                if (preg_match($reg, $subxml)) {
                    $arr[$key] = xml_to_array($subxml);
                } else {
                    $arr[$key] = $subxml;
                }
            }
        }
        return $arr;
    }
}


//获取远程图片类型
if (!function_exists('getRemoteImgType')) {
    function getRemoteImgType($url)
    {
        $type = '';
        $imgHeaderData = get_headers($url, 1);
        switch ($imgHeaderData['Content-Type']) {
            case 'image/png' :
                $type = 'png';
                break;
            case 'image/jpeg' :
                $type = 'jpg';
                break;
            case 'image/gif' :
                $type = 'gif';
                break;
            case 'image/bmp' :
                $type = 'bmp';
                break;
        }

        return $type;
    }
}

//下载文件
if (!function_exists('downloadFile')) {
    function downloadFile($filepath, $filename)
    {
        header('Content-Description: File Transfer');

        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename=' . $filename);
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        header('Content-Length: ' . filesize($filepath));
        readfile($filepath);
    }
}

/**
 * 自动去掉小数末尾的0
 * @param  float  $num [小数]
 * @return float       [返回去掉小数末尾0的小数]
 */
if (!function_exists('del0')) {
    function del0($s)
    {
        $s = trim(strval($s));
        if (preg_match('#^-?\d+?\.0+$#', $s)) {
            return preg_replace('#^(-?\d+?)\.0+$#','$1',$s);
        }
        if (preg_match('#^-?\d+?\.[0-9]+?0+$#', $s)) {
            return preg_replace('#^(-?\d+\.[0-9]+?)0+$#','$1',$s);
        }
        return $s;
    }
}

/**
 * @param $mobile
 * @return int
 * 判断是否是手机号
 */
if(!function_exists('isMobileNum')) {
    function isMobileNum($mobile)
    {
        return preg_match("/^13[\d]{9}$|^14[5,7]{1}\d{8}$|^15[^4]{1}\d{8}$|^17[0,3,6,7,8]{1}\d{8}$|^18[\d]{9}$/", $mobile);
    }
}
if(!function_exists('getMillisecond')) {
    function getMillisecond()
    {
        list($t1, $t2) = explode(' ', microtime());
        return (float)sprintf('%.0f', (floatval($t1) + floatval($t2)) * 1000);
    }
}